import React from 'react';
import ReactDom from 'react-dom';


/*
* 新的生命周期
*
* 弃用：componentWillReceiveProps / componentWillUpdate / componentWillMount
*   getDerivedStateFromProps /

*
* setTimeout用于延迟执行某方法或功能
setInterval则一般用于刷新表单，对于一些表单的假实时指定时间刷新同步
* */


const COLORS = ['red', 'blue', 'yellow', 'green'];

class ScrollList extends React.Component {
    constructor(props) {
        super(props);
        this.container = React.createRef();
        this.state = {messages: []}
    }

    addMessage = () => {
        this.setState({messages: [`${this.state.messages.length}`, ...this.state.messages]})

    };

    componentDidMount() {
        this.$timerID = window.setInterval(() => {
            this.addMessage()
        }, 500)
    }

    //获取dom"更新前"的快照（）：  被调用于render之后，
    getSnapshotBeforeUpdate(prevProps, prevState) {
        //scrollHeight  获取容器的内容高度
        return this.container.current.scrollHeight
    }

    //getSnapshotBeforeUpdate返回的任何值都将作为参数传递给componentDidUpdate()
    componentDidUpdate(prevProps, prevState, prevScrollHeight) {
        /*let scrollHeight = this.container.current.scrollHeight;
        let scrollTop = this.container.current.scrollTop + (scrollHeight - prevScrollHeight);
        this.container.current.scrollTop = scrollTop;
        console.log(prevScrollHeight)
        console.log(scrollHeight)
        console.log(scrollTop)*/

        const curScrollTop = this.container.current.scrollTop;//当前向上卷去的高度
        // console.log(curScrollTop === this.container.current.scrollHeight)  //  总的高度200px
        // console.log(this.container.current.scrollHeight - prevScrollHeight)    // 总高度一直在上升-之前的总高度：就是上升额元素的差值：
        console.log(prevScrollHeight,this.container.current.scrollHeight,this.container.current.scrollHeight - prevScrollHeight)

        //当前向上卷去的高度加上增加的内容高度
        this.container.current.scrollTop = curScrollTop + (this.container.current.scrollHeight - prevScrollHeight);

    }

    componentWillUnmount() {
        clearInterval(this.$timerID)
    }


    render() {
        let style = {
            height: '100px',
            width: '100px',
            overflow: 'auto',
            border: '0px solid green'

        }
        return (
            <div>
                <button onClick={()=>clearInterval(this.$timerID)}> stop</button>

                <div style={style} ref={this.container}>
                    {
                        //三个react元素
                        this.state.messages.map((message, index) => (
                            <div key={index} style={{backgroundColor: COLORS[index % 4]}}>{message}</div>
                        ))
                    }
                </div>
            </div>


        )
    }
}

ReactDom.render(<ScrollList/>, document.getElementById('root'));
